package com.dayu.finecomm.iot.handle;

import java.util.concurrent.CountDownLatch;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * IotPlat消息处理，URL解析
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
public class IotPlatSyncInboundHandler extends ChannelInboundHandlerAdapter {
	
	/**
	 * 同步计数器
	 */
	private CountDownLatch mLathc;
	
	/**
	 * 保存Content中的Json内容
	 */
	private volatile String mResult;
	
	/**
	 * 响应码
	 */
	private volatile int mCode;
	
	public IotPlatSyncInboundHandler(CountDownLatch lathc) {
		mLathc = lathc;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            mCode = response.getStatus().code();
        }
		
		if(msg instanceof HttpContent) {
			HttpContent content = (HttpContent)msg;
			String strContent = content.content().toString(io.netty.util.CharsetUtil.UTF_8);
			if (strContent.length() > 0) {
				mResult = new String(strContent);
			}
			
			mLathc.countDown();
		}
	}
	
	/**
	 * 重置CountDownLatch计数器
	 * @param initLathc CountDownLatch
	 */
	public void resetLatch(CountDownLatch initLathc) {
		mLathc = initLathc;
	}
	
	/**
	 * 返回Content中的JSON内容
	 * @return String
	 */
	public String getResult() {
		return mResult;
	}
	
	/**
	 * 返回URI
	 * @return
	 */
	public int getCode() {
		return mCode;
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		// IdleStateHandler所产生的IdleStateEvent的处理逻辑
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent)evt;
			
			switch(e.state()) {
			case ALL_IDLE:
				handleAllIdle(ctx);
				break;
			default:
				break;
			}
		}
	}
	
	/**
	 * 处理IdleStateHandler所产生的IdleStateEvent
	 * @param ctx ChannelHandlerContext
	 */
	protected void handleAllIdle(ChannelHandlerContext ctx) {
		ctx.channel().writeAndFlush("\r\n");
	}
}
